package mspbots.autotask.data.core;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @author Jay Yang
 */
public abstract class AbstractToolsUtil {

    protected R2dbcEntityTemplate r2dbcEntityTemplate;
    protected ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setR2dbcEntityTemplate(R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    protected LocalDateTime getDateTimeValue(JsonNode node){
        try {
            return ObjectUtils.isEmpty(node) || "null".equalsIgnoreCase(node.asText()) ? null : LocalDateTime.parse(node.asText(), DateTimeFormatter.ISO_DATE_TIME);
        }catch (DateTimeParseException ee){
            return ObjectUtils.isEmpty(node) || "null".equalsIgnoreCase(node.asText()) ? null : LocalDateTime.parse(node.asText(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        }catch (Exception e) {
            return null;
        }
    }
}
